package jp.test;

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.security.cert.Certificate;
import java.security.cert.CertificateFactory;

import org.cybergarage.http.HTTPRequest;
import org.cybergarage.http.HTTPRequestListener;
import org.cybergarage.http.HTTPResponse;
import org.cybergarage.soap.SOAPRequest;
import org.cybergarage.upnp.Action;
import org.cybergarage.upnp.Argument;
import org.cybergarage.xml.Attribute;
import org.cybergarage.xml.Node;

import sun.misc.BASE64Encoder;

public class SAServer implements HTTPRequestListener {

	
	public void httpRequestRecieved(HTTPRequest httpReq) {
		System.out.println("SA request received...");
		System.out.println("Message "+httpReq.toString());
		
		
		
		
		
		
		
		
	}
	
	public void connectDA(String name){
		//0. setting up
		String ipAddr = "";
		int port = 7000;
		if(name.equals("Jakky")){
			ipAddr = "172.30.137.79";
		}else{
			System.out.println("Unknow DA");
			return;
		}
		
		//1. exchange public key
		//1.1 load control point certificate
		certificatePath = "CA\\m0_cert\\newcert.der";
		byte[] certBytes = loadCertificate(certificatePath);
		BASE64Encoder base64Enc = new BASE64Encoder();
		String base64Cert = base64Enc.encode(certBytes);
		
		//1.3 send request to DA
		//Action getCertificate = groupControllerDevice.getAction("GetCertificate");
		//Argument certificateIn = getCertificate.getArgument("CertificateIn");
		//certificateIn.setValue(base64Cert);
		
		SOAPRequest req = new SOAPRequest();
		Node root = new Node();
		Attribute certificateAttr = new Attribute("LocalCertificate",base64Cert);
		root.addAttribute(certificateAttr);
		req.setContent(root);
		
		HTTPResponse res = req.post(ipAddr, port);
				
		//postaction control to get gc cert
		//if(getCertificate.postControlAction() == false)
		//	return;
		
		//2. receive group key and secret key
		
		//3. exchange peers
		
		
		
	}
	
	private String certificatePath = null;
	//load own certificate (will sent to network)
	private byte[] loadCertificate(String certPath){
		File certFile = new File(certPath);
		
		try{//read cacert file
			DataInputStream dis = new DataInputStream(new FileInputStream(certFile));
			CertificateFactory cf = CertificateFactory.getInstance("X509");
			Certificate cert = cf.generateCertificate(dis);
			
			
			return cert.getEncoded();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		return null;
	}

}
